package com.baike.job;



import com.baike.data.RedisName;
import com.baike.data.Result;
import com.baike.em.ConstantEnum;
import com.baike.entity.TbDiscount;
import com.baike.entity.TbLesson;
import com.baike.feign.TbDiscountsFeign;
import com.baike.feign.TbOrderFrign;
import com.baike.service.impl.TbDiscountServiceImpl;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.BoundListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Component
public class StartJob  {
    @Autowired
    private TbDiscountServiceImpl discountService;
    @Autowired
    private TbDiscountsFeign discountsFeign;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private TbOrderFrign orderFrign;

    @Scheduled(cron = "0 1 0 * * ?") //每天凌晨一分 执行
    public void startDiscount(){

        //团购缓存 大K
        BoundHashOperations hashOps = redisTemplate.boundHashOps(RedisName.GROUP_PURCHASE_PARENT);
        //死信队列 业务补偿


        //  把已经截止的课程 从团购转移到课程
        LambdaUpdateWrapper<TbDiscount> wrapper = Wrappers.<TbDiscount>lambdaUpdate()
                .lt(TbDiscount::getDiscountEndTime, new Date())
                .in(TbDiscount::getStatus, Arrays.asList(1, 3));


        List<TbDiscount> tbDiscountList = discountService.list(wrapper);
        if(tbDiscountList.size() > 0){
            TbLesson lesson = null;
           for(TbDiscount discount : tbDiscountList){
               //循环截止的课程 根据课程Id 获取最终拼团人数
               Long count  = (Long)hashOps.get(RedisName.GROUP_PURCHASE_BOY + discount.getDiscountId());
               // 如果满足拼团人数
               if(count >= discount.getStudentsNumber()){
                   // 发送订购成功的消息
                   System.out.println("订购成功");

               }else {
                   // 退还已定人员的 金额
                   BoundListOperations ops = redisTemplate.boundListOps(RedisName.GROUP_PURCHASE_LIST + discount.getDiscountId());
                   List range = ops.range(0, -1);
                   range.forEach( o ->{
                       String str = o.toString();
                       if(str.contains(".")){
                           String[] split = str.split(".");
                           if(split.length == 2){
                               Result result = orderFrign.alipayTradeRefundById(Long.valueOf(split[1]), Long.valueOf(split[0]));
                               if(result.getCode().equals(2000)){
                                   Result<ConstantEnum> result1 = discountsFeign.delHave(Long.valueOf(split[1]), new Long[]{Long.valueOf(split[0])});
                                   if(result1.getCode().equals(2000)){
                                       System.out.println("删除成功");
                                   }else {
                                       System.out.println("删除失败");
                                   }
                                   //退款成功
                                   System.out.println("退款已发送");
                               }else {
                                   // 添加死信息
                                   redisTemplate.boundListOps(RedisName.FAILURE_MESSAGE).leftPush(str);
                               }
                           }
                       }

                   });
               }

                // 构建普通课程 实体 将拼团课程数据转移到普通课程
               lesson = new TbLesson();
               lesson.setLessonId(discount.getDiscountId());
               lesson.setLessonName(discount.getDiscountLessonName());
               lesson.setLessonIntroduce(discount.getDiscountLessonIntroduce());
               lesson.setLessonCategories1(discount.getDiscountCategories1());
               lesson.setLessonCategories2(discount.getDiscountCategories2());
               lesson.setLessonImage(discount.getDiscountLessonImage());
               lesson.setLessonTeacherId(discount.getTeacherId());
               lesson.setLessonPublishDate(discount.getDiscountStartTime());
               lesson.setLessonStatus(discount.getStatus());
               lesson.setLessonDelete(0);
               lesson.setLessonFree(1);
               lesson.setLessonPrice(discount.getLessonPrice());
               lesson.setLessonCount(0L);
               lesson.setLessonGoal(discount.getDiscountLessonGoal());
               lesson.setLessonLabelIds(discount.getDiscountLessonLabelIds());
               lesson.setLessonLabelName(discount.getDiscountLessonLabelName());

               Result result = discountsFeign.postLess(lesson);
               System.out.println(result.getCode());
               // 如果转移成功
               if(result.getCode().equals(2000)){
                   //将拼团课程删除
                   boolean b = discountService.removeById(discount.getDiscountId());
                   //删除缓存
                   hashOps.delete(RedisName.GROUP_PURCHASE_BOY + discount.getDiscountId());
               }



           }
        }

    }
}
